package cn.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.SimpleFormatter;

import cn.bean.Play;
import cn.bean.Ticket;
import cn.bean.User;
import cn.dao.TicketDao;
import cn.dao.impl.TicketDaoImpl;
import cn.service.TicketService;

public class TicketServiceImpl implements TicketService
{
    TicketDao td=new TicketDaoImpl();

	@Override
	public boolean buyTicket(Play play, User user, int seat)
	{
		List<Ticket> lt=new ArrayList<Ticket>();
		if(user==null)   //锟斤拷未锟斤拷录
		{
			return false;
		}
		else
		{
			boolean isFlag=judgeSeat(play,seat);  //锟斤拷位锟窖憋拷锟斤拷
			if(isFlag)
			{
				return false;
			}
		}
		if(judgeNum(play, user))
		{
			return false;
		}
		Date now=new Date();     //锟斤拷取锟斤拷前时锟斤拷
		SimpleDateFormat fm=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String buy_time=fm.format(now);
		return td.doTicket(play, user, seat, buy_time);
	}

	@Override
	public boolean judgeSeat(Play play, int seat)
	{
		List<Ticket> lt=new ArrayList<Ticket>();
		lt=td.findTicketByPlay(play);
		for(Ticket t:lt)
		{
			if(t.getSeat()==seat) //锟斤拷锟斤拷位锟窖憋拷锟斤拷锟斤拷
			{
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean judgeNum(Play play, User user)
	{
		boolean isFlag=false;
		List<Ticket> lt=new ArrayList<Ticket>();
		lt=td.findTicketByPlay(play);
		int num=0;
		for(Ticket t:lt)
		{
			if(t.getUser().getId()==user.getId())
			{
				num++;
			}
		}
		if(num>=4)
		{
		    isFlag=true;
		}
		return isFlag;
	}

	//鏌ヨ鍦烘搴т綅鐘舵�侊紝0涓烘湭璁紝1涓哄凡璁紝绱㈠紩琛屼笌鍒楅兘浠�0寮�濮�
	@Override
	public int[][] seatStatus(Play play) {
		List<Ticket> lt=td.findTicketByPlay(play);
		int[][] seatStatus=new int[5][5];
		for(int i=0;i<5;i++)
		{
			for(int j=0;j<5;j++)
			{
				seatStatus[i][j]=0;
			}
		}
		for(Ticket t:lt)
		{
			for(int i=0;i<25;i++)
			{
				if(t.getSeat()==i)
				{
					if(i>=20)
					{
						int row=4;
						int cloum=i%5;
						seatStatus[row][cloum]=1;
					}
					else if(i>=15&&i<20)
					{
						int row=3;
						int cloum=i%5;
						seatStatus[row][cloum]=1;
					}
					else if(i>=10&&i<15)
					{
						int row=2;
						int cloum=i%5;
						seatStatus[row][cloum]=1;
					}
					else if(i>=5&&i<10)
					{
						int row=1;
						int cloum=i%5;
						seatStatus[row][cloum]=1;
					}
					else if(i>=0&&i<5)
					{
						int row=0;
						int cloum=i%5;
						seatStatus[row][cloum]=1;
					}
					break;
				}
				
			}			
		}
		return seatStatus;
	}

	@Override
	public String printSeat(int seat) {
		String s=null;
		int i=0;
		int j=0;
		if(seat%5>0)
		{
		i=(seat/5)+1;
		j=seat%5;
		}
		if(seat%5==0)
		{
			i=(seat/5);
			j=1;
		}
		s=i+"行"+j+"列";
		return s;
	}
}
